package com.team2.cyber_eye;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextThemeWrapper;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.team2.cyber_eye.ActivityHelpers.IQE;
import com.team2.cyber_eye.ActivityHelpers.Util;
import com.team2.cyber_eye.background_task.IQEngineProcessingTask;
import com.team2.cyber_eye.background_task.IQEngineProcessingTask.LoadingTaskFinishedListener;
import com.team2.shared.HistoryItem;

public class IQE_Progress extends CyberActivity implements LoadingTaskFinishedListener {

	Activity parent = this;
	Bitmap pictureBitmap = null;
	String progressMessage = "";
	String resultString = "";
	Bitmap progressPicture = null;
	final Activity activity = this;
	Timer progressTimer;
	String queryID = "";
	ProgressDialog progDialog;
	String iqeOrBarcode = "";	
	boolean displayError = false;
	String errorMessage = "";
	String barcodeText = "";
	long timeout = 180000;
	IQEngineProcessingTask obj;
	String filePath = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState, R.layout.activity_iqe_progress, "PROCESSING"); 

		try
		{
			if(Options.getSearchTimeout() > 0)
			{
				timeout = TimeUnit.MILLISECONDS.convert(Options.getSearchTimeout(), TimeUnit.MINUTES);
			}
		}
		catch(Throwable ex)
		{
			//WTF android????????
		}
		

		Bundle extras = this.getIntent().getExtras();
		if (extras != null)
		{
			iqeOrBarcode = (String)extras.get("iqeOrBarcode");
						
			try
			{
				if(iqeOrBarcode.equals("iqe")){
					
					Uri uri = this.getIntent().getData();
					
					if(uri != null){
						
						filePath = Util.FilePath(uri);
						pictureBitmap = Util.ReduceBitmap(getApplicationContext(), uri, 500);

					}
				}else if(iqeOrBarcode.equals("barcode")){
					
					pictureBitmap = (Bitmap)extras.get("photo");
					barcodeText = (String)extras.get("barcode");
				}
				
				if (pictureBitmap != null)
				{
					Bitmap scaledBitmap = Util.LimitBitmap(pictureBitmap, 200);
					
					ImageView imageView = (ImageView)activity.findViewById(R.id.imageLogo);
					
					Bitmap rotatedBitmap = Util.RotateBitmap(scaledBitmap, filePath);
					
					if(rotatedBitmap != null){
						imageView.setImageBitmap(rotatedBitmap);
					}else{
						imageView.setImageBitmap(scaledBitmap);
					}
					
					/*Matrix matrix = new Matrix();
					matrix.postRotate(90);
					Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, 
							scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
				    
				    ImageView imageView = (ImageView)activity.findViewById(R.id.imageLogo);
					imageView.setImageBitmap(rotatedBitmap);*/
				}
						
			}
			catch (Exception ex)
			{
				Util.DisplayError(this, "Error loading image", ex);
			}
		}


		if (pictureBitmap != null) 
		{
			
			showDialog(0);

			obj = new IQEngineProcessingTask(this, this);
			
			ArrayList<Object> objectList = new ArrayList<Object>();
			
			objectList.add(pictureBitmap);
			objectList.add(iqeOrBarcode);
			objectList.add(barcodeText);
			
			obj.execute(objectList);

			Handler handler = new Handler();
			handler.postDelayed(new Runnable()
			{
				@Override
				public void run() {
					if ( !Util.isTaskCompleted() && obj.getStatus() == Status.RUNNING )
					{
						obj.cancel(true);
						progDialog.dismiss();
						
						new AlertDialog.Builder(new ContextThemeWrapper(parent, R.style.Theme_MyDialog))
			            .setIcon(android.R.drawable.ic_dialog_alert)
			            .setTitle("")
			            .setMessage("Sever is busy. Perform manual search?")
			            .setPositiveButton("Yes", new DialogInterface.OnClickListener()
				        {
				            @Override
				            public void onClick(DialogInterface dialog, int which) {
				            	Intent intent = new Intent(parent, SearchByText.class);
				            	parent.startActivity(intent);   
				            	parent.finish();
				            }
				
				        })
				        .setNegativeButton("No", new DialogInterface.OnClickListener()
				        {
				            @Override
				            public void onClick(DialogInterface dialog, int which) {
				            	parent.finish();    
				            }
				
				        })
				        .show();
					}			
				}
			}, timeout );
		}
		else
		{
			Util.DisplayIssue(this, "Unable to load the picture");
		}
	}

	@Override
	protected Dialog onCreateDialog(int id){
		progDialog = new ProgressDialog(this, R.style.Theme_MyDialog);
		progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progDialog.setTitle("In Progress");
		if(iqeOrBarcode.equals("iqe")){
			progDialog.setMessage("Processing Image...");
		}else if(iqeOrBarcode.equals("barcode")){
			progDialog.setMessage("Processing Barcode...");
		}
		
		progDialog.setCanceledOnTouchOutside(false);
		progDialog.setCancelable(true);
		return progDialog;
	}

	@Override
	public void onTaskFinished(ArrayList<String> resultList) {

		Util.setTaskCompleted(true);
		obj.cancel(true);
		if(resultList != null && resultList.size() > 0){

			String error = resultList.get(2);

			if (error.length() > 0)
			{
				progDialog.dismiss();
				Util.DisplayIssue(this, error);
				finish();
			}
			else if (error.length() == 0)
			{		
				progDialog.dismiss();
				Intent intent = new Intent();
				intent.putExtra("name", resultList.get(0));
				intent.putExtra("queryId", resultList.get(1));
				parent.setResult(Activity.RESULT_OK, intent);								
				finish();
			}
		}else{
			Util.DisplayMessage(getApplicationContext(), "Unable to match the image");
			finish();
		}
	}

}
